from typing import List, Dict, Any, Optional
from .base import BaseRetriever
from ..vectorstore.base import BaseVectorStore

class VectorRetriever(BaseRetriever):
    def __init__(self, vectorstore: BaseVectorStore, k: int = 4):
        """
        初始化向量检索器
        参数:
            vectorstore: 向量存储实例
            k: 返回的最相似文档数量
        """
        self.vectorstore = vectorstore
        self.k = k

    def get_relevant_documents(self, query: str, k: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        检索相关文档
        """
        try:
            print("\n=== 开始文档检索 ===")
            k = k or self.k
            print(f"检索参数 - 查询: {query}, k: {k}")
            
            results = self.vectorstore.similarity_search(query, k=k)
            print(f"检索到原始结果数量: {len(results)}")
            
            # 确保返回结果格式统一
            formatted_results = []
            for i, doc in enumerate(results):
                print(f"\n处理第 {i+1} 个检索结果:")
                try:
                    formatted_doc = {
                        "content": doc.get("content", ""),
                        "metadata": doc.get("metadata", {}),
                        "score": doc.get("score", 0.0)
                    }
                    print(f"  - 内容长度: {len(formatted_doc['content'])}")
                    print(f"  - 元数据: {formatted_doc['metadata']}")
                    print(f"  - 分数: {formatted_doc['score']}")
                    formatted_results.append(formatted_doc)
                except Exception as e:
                    print(f"  - 格式化结果时出错: {str(e)}")
            
            print(f"\n最终返回 {len(formatted_results)} 个文档")
            return formatted_results
            
        except Exception as e:
            print("\n=== 文档检索出错 ===")
            print(f"错误类型: {type(e).__name__}")
            print(f"错误信息: {str(e)}")
            return []
